import React, { useMemo } from 'react';
import { useSelector } from 'react-redux';
import { MODULE_TYPES } from '@ohif/core';
import { Menu, Submenu, Item, Separator, theme } from 'react-contexify';
import { TOOLBAR_BUTTON_TYPES } from '@ohif/core';
import { useTranslation } from 'react-i18next';
import { Icon } from '../../icons';
import isDisplaySetReconstructable from '../../utils/isDisplaySetReconstructable';

import 'react-contexify/dist/ReactContexify.css';
import './ContextMenu.styl';

const ContextMenu = ({ onItemClick, extensionManager }) => {
  const { t } = useTranslation('Buttons');

  const buttonIcon = button => {
    const btnIcon = button.icon;
    if (btnIcon) {
      if (typeof btnIcon === 'string') {
        return <Icon name={btnIcon} />;
      } else {
        const CIcon = btnIcon;
        return <CIcon />;
      }
    }
    return null;
  };

  const isDisabled = id => {
    if (id && id.startsWith('vtk')) {
      const { viewportSpecificData, activeViewportIndex } = useSelector(
        state => {
          const modeState = state.viewports[state.viewports.viewMode] || {};
          const { viewportSpecificData, activeViewportIndex } = modeState;

          return {
            viewportSpecificData,
            activeViewportIndex,
          };
        }
      );
      return !isDisplaySetReconstructable(
        viewportSpecificData,
        activeViewportIndex
      );
    }

    return false;
  };

  const menuGroups = useMemo(() => {
    const groups = {};
    const toolbarModules = extensionManager.modules[MODULE_TYPES.TOOLBAR];
    const viewportModules = extensionManager.modules[MODULE_TYPES.VIEWPORT];
    viewportModules.forEach(extension => {
      let toolbarExtension;
      toolbarModules.forEach(tb => {
        if (tb.extensionId === extension.extensionId) {
          toolbarExtension = tb;
        }
      });
      const { definitions, defaultContext } = toolbarExtension.module;
      definitions.forEach(d => {
        const cxt = d.context || defaultContext;
        if (!groups[cxt]) {
          groups[cxt] = [d];
        } else {
          groups[cxt].push(d);
        }
      });
    });
    return groups;
  }, [extensionManager.modules]);

  const handleItemClick = ({ data: btn, event: evt }) => {
    if (onItemClick) {
      onItemClick(btn, evt);
    }
  };

  const Menus = (
    <>
      {Object.keys(menuGroups).map((k, i) => {
        const g = menuGroups[k];
        return (
          <Menu key={k} id={k} theme={theme.dark}>
            {g.map(b => {
              if (b.buttons && b.buttons.length) {
                return (
                  <Submenu
                    key={b.id}
                    label={(<>
                      <div className="item-icon">{buttonIcon(b)}</div>
                      <div className="item-text">{t(b.label)}</div>
                    </>)}>
                    {b.buttons.map(sb => {
                      return sb.type === TOOLBAR_BUTTON_TYPES.DIVIDER ? (
                        <Separator key={sb.id} />
                      ) : (
                        <Item
                          key={sb.id}
                          data={sb}
                          disabled={isDisabled(sb.id)}
                          onClick={handleItemClick}
                        >
                          <div className="item-icon">{buttonIcon(sb)}</div>
                          <div className="item-text">{t(sb.label)}</div>
                        </Item>
                      );
                    })}
                  </Submenu>
                );
              } else {
                return b.type === TOOLBAR_BUTTON_TYPES.DIVIDER ? (
                  <Separator key={b.id} />
                ) : (
                  (!b.nonContexify) ? (
                    <Item
                      key={b.id}
                      data={b}
                      disabled={isDisabled(b.id)}
                      onClick={handleItemClick}
                    >
                      <div className="item-icon">{buttonIcon(b)}</div>
                      <div className="item-text">{t(b.label)}</div>
                    </Item>
                  ) : null
                );
              }
            })}
          </Menu>
        );
      })}
    </>
  );

  return <div className="context-menu">{Menus}</div>;
};

export default ContextMenu;
